﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Wise.Util
{
    /// <summary>
    /// 集合类扩展
    /// </summary>
    public static class CollectionExtension
    { 
        ///// <summary>
        ///// 重设键值对的可读写性
        ///// </summary>
        ///// <param name="request"></param>
        ///// <param name="_readonly"></param>
        //public static void ResetReadonly(this NameValueCollection request, bool _readonly)
        //{
        //    MyNameValueCollection.ResetReadOnly(request, _readonly);
        //}

        /// <summary>
        /// 将键值对集合改为字典
        /// </summary>
        /// <param name="nvc"></param>
        /// <returns></returns>
        public static Dictionary<string, string> ToDictionary(this NameValueCollection nvc)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            for (int i = 0; i < nvc.Keys.Count; i++)
            {
                string key = nvc.Keys[i];
                dic.Add(key, nvc[key]);
            }
            return dic;
        }

        /// <summary>
        /// 将字典改为键值对集合
        /// </summary>
        /// <param name="nvc"></param>
        /// <returns></returns>
        public static NameValueCollection ToNameValueCollection(this Dictionary<string, string> nvc)
        {
            NameValueCollection dic = new NameValueCollection();
            foreach (string key in nvc.Keys)
            {
                dic.Add(key, nvc[key]);
            }
            return dic;
        }

        /// <summary>
        /// 将字典改为键值对集合
        /// </summary>
        /// <param name="nvc"></param>
        /// <returns></returns>
        public static NameValueCollection ToNameValueCollection(this Dictionary<string, object> nvc)
        {
            NameValueCollection dic = new NameValueCollection();
            foreach (string key in nvc.Keys)
            {
                object obj = nvc[key];
                if (obj == null)
                    continue;
                string val = obj.ToString();
                val = val.Trim('"');
                dic.Add(key, val);
            }
            return dic;
        }

        /// <summary>
        /// 如果列表不为空。则追加数据
        /// </summary>
        /// <typeparam name="TModel"></typeparam>
        /// <param name="list"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static List<TModel> AppendIfNotNull<TModel>(this List<TModel> list, params TModel[] data)
        {
            if (data.Length == 0 || list == null || list.Count == 0)
                return list;
            list.AddRange(data);
            return list;
        }
    }
}
